<template>
  <el-dialog v-model="visible" :title="query?.title" width="1000" draggable :before-close="isClosed" :close-on-click-modal="false" center append-to-body>
    <div class="supplier-item">
        <el-collapse v-model="activeName" @change="handleChange" accordion class="supplier-list">
            <el-collapse-item v-if="query.type != 'addBusiness'" title="基本信息" name="1">
                <el-form label-width="auto" :model="formData.basicInf" ref="formBasic" :rules="pageData.supplierRules.basicInf">
                    <el-form-item label="供应商名称：" prop="supplierName" style="width: 98%">
                        <el-input placeholder="供应商名称" v-model="formData.basicInf.supplierName" maxlength ="50" show-word-limit :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item label="产品及服务：" style="width: 98%">
                        <el-input placeholder="请输入内容" v-model="formData.basicInf.proAndSer" type="textarea" maxlength="300" show-word-limit :rows="6" :disabled="isDisabled" :close-on-click-modal="false"/>
                    </el-form-item>
                </el-form>
            </el-collapse-item>
            <el-collapse-item v-if="query.type != 'addBusiness'" title="企业概况" name="2">
              <div class="collapse-content">
                <el-form label-width="auto" :model="formData.enterpriseProfile" :inline="true" ref="formProfile" :rules="pageData.supplierRules.enterpriseProfile">
                    <el-form-item label="公司地址：" prop="address" style="width: 29%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.address" type="textarea" maxlength ="30" autosize show-word-limit :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item label="成立时间：" style="width: 29%">
                        <el-date-picker v-model="formData.enterpriseProfile.establishmentDate" type="date" placeholder="选择时间" :size="size" format="YYYY/MM/DD" value-format="YYYY-MM-DD" :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item label="注册资金：" style="width: 29%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.registeredCapital" type="Number" :disabled="isDisabled">
                            <template #append>
                                万元
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="法人代表：" prop="legalPerson" style="width: 29%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.legalPerson" :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item label="联系电话：" prop="legalPersonPhone" style="width: 29%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.legalPersonPhone" :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item label="传真号码：" style="width: 29%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.faxNumber" :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item label="授权联系人：" prop="authorizer" style="width: 29%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.authorizer" :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item label="职务：" style="width: 29%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.position" :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item label="手机号码：" prop="authorizerPhone" style="width: 29%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.authorizerPhone" :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item label="公司网址：" style="width: 96%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.website" :disabled="isDisabled">
                            <template #prepend>Http://</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="经营模式：" style="width: 96%">
                        <el-radio-group v-model="formData.enterpriseProfile.businessModel" :disabled="isDisabled">
                            <el-radio value="生产厂家">生产厂家</el-radio>
                            <el-radio value="代理商">代理商</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="企业性质：" style="width: 96%">
                        <el-radio-group v-model="formData.enterpriseProfile.enterpriseNature" :disabled="isDisabled">
                            <el-radio value="国有企业">国有企业</el-radio>
                            <el-radio value="集体企业">集体企业</el-radio>
                            <el-radio value="民营企业">民营企业</el-radio>
                            <el-radio value="外商独资">外商独资</el-radio>
                            <el-radio value="中外合资">中外合资</el-radio>
                            <el-radio value="个体">个体</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="纳税人性质：" style="width: 46%">
                        <el-radio-group v-model="formData.enterpriseProfile.natureOfTaxpayer" :disabled="isDisabled">
                            <el-radio value="一般纳税人">一般纳税人</el-radio>
                            <el-radio value="小规模纳税人">小规模纳税人</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="纳税人登记号：" style="width: 47%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.registrationNumber" :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item label="收款单位：" style="width: 96%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.receivingParty" :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item label="收款银行：" style="width: 96%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.receivingBank" :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item label="收款账户：" prop="receivableAccount" style="width: 96%">
                        <el-input placeholder="请输入内容" v-model="formData.enterpriseProfile.receivableAccount" :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item style="width: 96%">
                        <template #label>
                            <div>
                            三年内是否有<br/>法律纠纷、是<br/>否被政府部门<br/>处罚：
                            </div>
                        </template>
                        <el-input placeholder="若没有填“无”即可" v-model="formData.enterpriseProfile.legalDisputes" type="textarea" maxlength="300" show-word-limit :rows="6" :disabled="isDisabled"/>
                    </el-form-item>
                </el-form>
              </div>
            </el-collapse-item>
            <el-collapse-item v-if="query.type != 'addBusiness'" title="组织机构" name="3">
                <el-form label-width="auto" :model="formData.organizationOrInstitution" :inline="true">
                    <el-form-item label="职工总数：" prop="totalNumberOfEmployees" style="width: 30%">
                        <el-input-number v-model="formData.organizationOrInstitution.totalNumberOfEmployees" controls-position="right" :disabled="isDisabled">
                            <template #suffix>
                                <span>人</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="管理人员：" prop="managers" style="width: 30%">
                        <el-input-number v-model="formData.organizationOrInstitution.managers" controls-position="right" :disabled="isDisabled">
                            <template #suffix>
                                <span>人</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="技术人员：" prop="technician" style="width: 30%">
                        <el-input-number v-model="formData.organizationOrInstitution.technician" controls-position="right" :disabled="isDisabled"> 
                            <template #suffix>
                                <span>人</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="营销人员：" prop="marketers" style="width: 30%">
                        <el-input-number v-model="formData.organizationOrInstitution.marketers" controls-position="right" :disabled="isDisabled">
                            <template #suffix>
                                <span>人</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="行政管理：" prop="administrator" style="width: 30%">
                        <el-input-number v-model="formData.organizationOrInstitution.administrator" controls-position="right" :disabled="isDisabled">
                            <template #suffix>
                                <span>人</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="工人：" prop="worker" style="width: 30%">
                        <el-input-number v-model="formData.organizationOrInstitution.worker" controls-position="right" :disabled="isDisabled">
                            <template #suffix>
                                <span>人</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                </el-form>
            </el-collapse-item>
            <el-collapse-item v-if="query.type != 'addBusiness'" title="主要业绩" name="4">
                <el-form label-width="auto" :model="formData.mainAchievements" :inline="true">
                    <el-form-item style="width: 96%">
                        <template #label>
                            <div>
                            近三年的<br/>年度营业<br/>额：
                            </div>
                        </template>
                        <el-input v-model="formData.mainAchievements.turnover1" placeholder="请输入内容" :disabled="isDisabled">
                            <template #prepend>
                                <el-date-picker v-model="formData.mainAchievements.annual1" type="year" placeholder="选择年份" :size="size" :disabled="isDisabled"/>
                            </template>
                            <template #append>
                                万元
                            </template>
                        </el-input>
                        <el-input v-model="formData.mainAchievements.turnover2" placeholder="请输入内容" :disabled="isDisabled">
                            <template #prepend>
                                <el-date-picker v-model="formData.mainAchievements.annual2" type="year" placeholder="选择年份" :size="size" :disabled="isDisabled"/>
                            </template>
                            <template #append>
                                万元
                            </template>
                        </el-input>
                        <el-input v-model="formData.mainAchievements.turnover3" placeholder="请输入内容" :disabled="isDisabled">
                            <template #prepend>
                                <el-date-picker v-model="formData.mainAchievements.annual3" type="year" placeholder="选择年份" :size="size" :disabled="isDisabled"/>
                            </template>
                            <template #append>
                                万元
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="年度供货能力：" style="width: 30%">
                        <el-input placeholder="请输入内容" v-model="formData.mainAchievements.annualSupplyCapacity" show-word-limit :disabled="isDisabled">
                            <template #append>
                                万元
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="服务区域范围：" style="width: 63%">
                        <el-input placeholder="请输入内容" v-model="formData.mainAchievements.serviceAreaScope" show-word-limit :disabled="isDisabled"/>
                    </el-form-item>
                    <el-form-item style="width: 96%">
                        <el-input placeholder="请输入内容" v-model="formData.mainAchievements.quantityAndScale" type="textarea" maxlength="200" show-word-limit :rows="4" :disabled="isDisabled"/>
                        <template #label>
                            <div>
                            目前在建<br/>项目数量<br/>及规模：
                            </div>
                        </template>
                    </el-form-item>
                </el-form>
            </el-collapse-item>
            <el-collapse-item v-if="query.type != 'add'" title="与我司业务" name="5">
                <div class="table-box">
                    <el-table
                        :data="tableData"
                        style="width: 100%">
                        <el-table-column width="55" fixed>
                            <template #default="{ row }">
                                <el-radio
                                    class="radio"
                                    :label="row"
                                    v-model="currentRow"
                                    :disabled="isDisabled">
                                    &emsp;&emsp;&emsp;
                                </el-radio>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" width="55" fixed />
                        <el-table-column prop="product_name" label="&nbsp&nbsp&nbsp商品名称" width="180" fixed />
                        <el-table-column label="产品类型" width="100">
                            <template #default="{ row }">
                                {{ translateType(row.type) }} 
                            </template>
                        </el-table-column>
                        <el-table-column prop="brand_or_style" label="牌号/款式"  width="180" />
                        <el-table-column prop="internal_brand" label="内部牌号"  width="180" />
                        <el-table-column prop="specification" label="规格" width="180" />
                        <el-table-column label="单价" width="100">
                            <template #default="{ row }">
                                {{ row.unit_price + row.priceUnit }} 
                            </template>
                        </el-table-column>
                        <el-table-column label="年总需求（数量/重量）" width="180">
                            <template #default="{ row }">
                                {{ row.totalProductQuantity ? row.totalProductQuantity + row.quantityUnit : "未记录" }} / {{ row.totalProductWeight ? row.totalProductWeight + row.weightUnit : "未记录" }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="totalProductSum" label="总金额" width="100" />
                        <el-table-column prop="signingDate" label="签订时间" width="180" />
                        <el-table-column label="有效期" width="100">
                            <template #default="{ row }">
                                {{ row.validityPeriod + "月" }} 
                            </template>
                        </el-table-column>
                        <el-table-column label="费用率" width="100">
                            <template #default="{ row }">
                                {{ row.costRate + "%" }} 
                            </template>
                        </el-table-column>
                        <el-table-column label="采购成本管理" width="180" fixed="right">
                            <template #default="{ row }">
                                <el-button v-if="!row.totalFee" @click="handleComponent('addCost',row)" type="primary">填写采购成本单</el-button>
                                <el-link type="warning" @click="handleComponent('editCost',row)" v-if="row.totalFee">{{ row.totalFee }}元</el-link type="warning">
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style="margin-top: 20px">
                        <el-button v-if="!isDisabled" type="primary" @click="handleComponent('add')">新增业务</el-button>
                        <el-button v-if="!isDisabled" type="primary" @click="handleComponent('edit')">编辑业务</el-button>
                        <el-button v-if="!isDisabled" type="info" @click="handleComponent('del')">删除业务</el-button>
                    </div>
                    <Edit :query="formQuery" :supplierId="query?.id" :dialogVisible="dialogEditVisible" @updateData="updateData" :getbusinessList="getbusinessList"/>
                    <simpleCostEdit :query="formQuery" :dialogVisible="dialogCostEditVisible" @updateData="updateData" :getList="getbusinessList"/>
                </div>
            </el-collapse-item>
        </el-collapse>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="!isDisabled" @click="isClosed">取消</el-button>
        <el-button v-if="!isDisabled && query.type != 'addBusiness'" type="primary" @click="submit">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts">
import { defineComponent, onBeforeMount, reactive, toRefs, ref, PropType, watch, computed } from 'vue'
import { supplierAdd, supplierDetails, supplierUpdate, businessPage, businessDelete } from "../service/api"
import type { ComponentSize, FormInstance, FormRules} from 'element-plus'
import { ElMessage, ElMessageBox } from "element-plus";
import Edit from './businessEdit.vue'
import simpleCostEdit from './simpleCostEdit.vue'
import pageData from '../service/pageService'
export default defineComponent({
    name: 'Pagination',
    components: {
        Edit,
        simpleCostEdit,
    },
    props: {
      query: {
        type: Object,
        default: () => ({})
      },
      dialogVisible: {
        type: Boolean,
        default: false
      },
      getList:{
        type:Function,
        default: () => () => {}
      },
      getAllSupplier:{
        type:Function,
        default: () => () => {}
      },
    },
    setup(props,{emit}) {
      const state = reactive({
        btnLoading: false,
        visible: false,
        currentRow:null,
        formQuery:null,
        dialogEditVisible:null,
        dialogCostEditVisible:false,
        activeName: ref('0'),
        formData:{
            basicInf:{
                supplierName: null,
                proAndSer: null,
            },
            enterpriseProfile:{
                address: null,
                establishmentDate: null,
                registeredCapital: null,
                legalPerson: null,
                legalPersonPhone: null,
                faxNumber: null,
                authorizer: null,
                position: null,
                authorizerPhone: null,
                website: null,
                businessModel: null,
                enterpriseNature: null,
                natureOfTaxpayer: null,
                registrationNumber: null,
                receivingParty: null,
                receivingBank: null,
                receivableAccount: null,
                legalDisputes: null,
            },
            organizationOrInstitution:{
                totalNumberOfEmployees: null,
                managers: null,
                technician: null,
                marketers: null,
                administrator: null,
                worker: null,
            },
            mainAchievements:{
                annual1: null,
                turnover1: null,
                annual2: null,
                turnover2: null,
                annual3: null,
                turnover3: null,
                annualSupplyCapacity: null,
                serviceAreaScope: null,
                quantityAndScale: null,
            }
        },
        tableData:[
            // {
            //     id:1,
            //     product_name:"氧化铝铜板",
            //     brand_or_style:"C15760",
            //     internal_brand:"C15760",
            //     totalProductQuantity:30,
            //     quantityUnit:"pcs",
            //     unit_price: 2,
            //     priceUnit: "元/kpcs",
            //     unit_price: 10,
            //     totalProductSum:14511.24,
            //     type: 2, //产品种类 1-原料，2-产品，3-其他
            //     signingDate: '2016-05-02', //签订时间
            //     validityPeriod: 12, //有效期
            //     costRate: 3, //单位产品库存年维持费用率
            //     specification: "L3000*W82*T30",
            // },
            // {
            //     id:2,
            //     product_name:"氧化铝铜管",
            //     brand_or_style:"C18150",
            //     internal_brand:"C15760",
            //     totalProductWeight:50,
            //     weightUnit:"kg",
            //     unit_price: 2,
            //     priceUnit: "元/kg",
            //     totalProductSum:9612.00,
            //     type: 1, //产品种类 1-原料，2-产品，3-其他
            //     signingDate: '2017-12-30', //签订时间
            //     validityPeriod: 16, //有效期
            //     costRate: 6, //单位产品库存年维持费用率
            //     specification: "D89*d22*L350",
            //     totalFee: 125,
            // }
        ],
      })
      // 计算属性，根据 query.type 判断只读属性
      const isDisabled = computed(() => {
        return props.query?.type === "view";
      })
      //判断产品类型
      const translateType = (val) => {
          if(val === 1) return "原料"
          else if(val === 2) return "产品"
          else return "其他"
      }
      const handleComponent = (val,row=state.currentRow) => {
        if(val == "edit")
        {
            if(!state.currentRow){
                ElMessage({
                    message: '请选择需要被编辑的数据行',
                    type: 'warning',
                })
            }
            else{
                const data = {
                    type:val,
                    title:"编辑",
                    id:row.id
                }
                state.formQuery = data
                state.dialogEditVisible = true
            }
            console.log("state.currentRow",state.currentRow)
        }else if(val == "add")
        {
            const data = {
                type:val,
                title:"新增"
            }
            state.formQuery = data
            state.dialogEditVisible = true
        }else if(val == "del")
        {
            if(!state.currentRow){
                ElMessage({
                    message: '请选择需要被删除的数据行',
                    type: 'warning',
                })
            }
            else{
                businessDelete(props.query?.id , row.id).then((res)=>{
                    ElMessage({
                        message: '删除成功',
                        type: 'success',
                    })
                    getbusinessList()
                })
            }
        }else if(val == "addCost")
        {
            console.log("addCost",row)
            const data = {
                type:val,
                title:"订货成本表单",
                businessId:row?.id,
                supplierId:props.query?.id,
                supplierName:props.query?.supplierName,
                product_name:row?.product_name
            }
            state.formQuery = data
            state.dialogCostEditVisible = true
        }else if(val == "editCost")
        {
            const data = {
                type:val,
                title:"编辑订货成本表单",
                businessId:row?.id,
                supplierId:props.query?.id,
                product_name:row?.product_name
            }
            state.formQuery = data
            state.dialogCostEditVisible = true
        }
      }
      //用于关闭业务弹窗
      const updateData = (val) =>{
        state.dialogEditVisible = val
        state.dialogCostEditVisible = val
        console.log("state.dialogVisible ",state.dialogEditVisible )
      }
      //用于关闭供应商列表单弹窗
      const isClosed = () =>{
        state.visible = false
        emit('updateData', state.visible)
      }
      watch(() => props.dialogVisible, () => {
        state.visible = props.dialogVisible
        state.activeName = "0"
        initData()
        if(props.query?.type != 'add') getbusinessList()
        console.log("query",props.query)
      })
      const initData = () => {
        console.log("props.query",props.query)
        if(props.query?.type == 'edit' || props.query?.type == 'view') {
          const params = {
            id:props.query?.id
          }
          supplierDetails(params).then((res)=>{
            console.log('res',res)
            state.formData = res.data.data
          }).catch((error) => {
            console.error('无法获取数据', error);
          });
        }else if (props.query?.type == 'add') {
            state.formData = JSON.parse(JSON.stringify(pageData.initSupplierData))
        }
      }
      const getbusinessList = () => {
        businessPage(props.query?.id).then((response)=>{
            state.tableData = response.data.data
            console.log("Response:", response.data.data);
        })
      }
      const formBasic = ref<FormInstance>()
      const formProfile = ref<FormInstance>()
      const submit = () => {
        // 并行验证所有表单
        formBasic.value.validate((valid) => {
            if (valid) { 
                formProfile.value.validate((valid) => {
                    if (valid) { 
                        state.btnLoading = true
                        state.formData.enterpriseProfile.registeredCapital = Number(state.formData.enterpriseProfile.registeredCapital)
                        state.formData.mainAchievements.turnover1 = Number(state.formData.mainAchievements.turnover1)
                        state.formData.mainAchievements.turnover2 = Number(state.formData.mainAchievements.turnover2)
                        state.formData.mainAchievements.turnover3 = Number(state.formData.mainAchievements.turnover3)
                        state.formData.mainAchievements.annualSupplyCapacity = Number(state.formData.mainAchievements.annualSupplyCapacity)
                        console.log("state.formData",state.formData)
                        if(props.query.type == 'edit'){
                            supplierUpdate(props.query?.id,state.formData).then((res)=>{
                                ElMessage.success("保存成功！")
                                props.getList()
                                isClosed(); // 关闭弹窗
                                state.btnLoading = false
                            })
                        }else if(props.query.type == 'add'){
                            supplierAdd(state.formData).then((res)=>{
                                ElMessage.success("保存成功！")
                                props.getList()
                                props.getAllSupplier()
                                isClosed(); // 关闭弹窗
                                state.btnLoading = false
                            })
                        }
                        console.log("供应商登记表",state.formData)
                } else {
                    // 有表单验证失败，提示用户
                    ElMessage.warning('请检查企业概况必填项');
                    state.btnLoading = false;
                  }
                })
            } else {
                // 有表单验证失败，提示用户
                ElMessage.warning('请检查供应商基本信息必填项');
                state.btnLoading = false;
              }
            })
      }
      onBeforeMount(() => {
        console.log('query.type',props.query?.type)
      })
      return {
        ...toRefs(state),
        isClosed,
        formBasic,
        formProfile,
        pageData,
        submit,
        handleComponent,
        updateData,
        isDisabled,
        getbusinessList,
        translateType
      }
    }
})
</script>
<style scoped>
.layout{
    width: auto;
    height: 800px;
    background-color: #FFFFFF;
}
.collapse-content{
    max-height: 300px; /* 设置最大高度 */
    overflow-y: auto; /* 超出高度时显示竖向滚动条 */
}
</style>
  